package com.etop.dao;

import com.etop.beans.*;
import com.etop.utils.MD5;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.web.multipart.MultipartFile;

public class UserDao {

    private SessionFactory sessionFactory;
    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD");

    public SessionFactory getSessionFactory() {
        return sessionFactory;

    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
        System.out.println(this.sessionFactory);
    }

    protected Session getSession() {
        return getSessionFactory().getCurrentSession();
    }

    /**
     * 登陆验证
     *
     * @param user
     * @return
     */
    public User loginValidate(User user) {
        String checkSql = "from User where stu_num = ?";
        List<User> uL = this.getSession().createQuery(checkSql)
                .setParameter(0, user.getStuNum()).list();

        if (uL.size() != 0) {
            User u = uL.get(0);
            if (!new MD5().getkeyBeanofStr(user.getPassword()).equals(u.getPassword())) {
                return null;
            } else {
                return u;

            }
        }
        return null;
    }

    /**
     * 添加物品到数据库
     *
     * @param g
     */
    public void addGoods(Goods g) {
        this.getSession().save(g);
    }

    /**
     * 添加借取记录到数据库
     *
     * @param borrow
     */
    public void addBorrow(Borrow borrow) {
        this.getSession().save(borrow);
    }

    /**
     * 通过文件Id找到文件
     *
     * @param proFileId
     * @return
     */
    public ProFile loadProFileById(int proFileId) {
        return (ProFile) this.getSession().createQuery("from ProFile where id = :pid").setInteger("pid", proFileId).uniqueResult();
    }

    /**
     * 通过projectId找到对应的project
     *
     * @param projectId
     * @return
     */
    public Project loadProjectById(Integer projectId) {
        System.out.println("pid:" + projectId);
        return (Project) this.getSession().createQuery("from Project where id = :pid").setInteger("pid", projectId).uniqueResult();
    }

    /**
     * 处理上传文件
     *
     * @param multipartFile
     * @param proFile
     * @param contextPath
     */
    public void addProFile(MultipartFile multipartFile, ProFile proFile, String contextPath) {
        String fileName = UUID.randomUUID().toString() + "_" + multipartFile.getOriginalFilename();
        //创建保存文件的目录：主目录+LabRegistration+proFile+项目名
        String savePath = contextPath + "/WEBINF/ProFile/" + proFile.getProject().getName();
        File f = new File(savePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        System.out.println(f.getAbsolutePath());
        //同时在proFile中记录文件的位置以便写入数据库保存
        proFile.setFile(savePath + '/' + fileName);

        try {
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(proFile.getFile()));
        } catch (IOException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.getSession().save(proFile);
    }

    /**
     * 列出所有项目
     *
     * @return
     */
    public List<Project> listProject() {
        return this.getSession().createQuery("from Project").list();
    }

    /**
     * 取出所有名字中含有proName的文件
     *
     * @param proName
     * @return
     */
    public List<ProFile> listProFile(String proName) {
        return this.getSession().createQuery("from ProFile where project.name like ?").setParameter(0, "%" + proName + "%").list();
    }

    /**
     * 判断是否已经加入活动
     *
     * @param user
     * @param act
     * @return
     */
    public boolean isAddActivity(User user, Activity act) {
        String checkSql = "from User_activity where u_id = ? and act_id = ?";
        Query query = this.getSession().createQuery(checkSql);
        query.setParameter(0, user.getId());
        query.setParameter(1, act.getId());
        List uL = query.list();
        if (uL.size() != 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 将Activity的内容以list的形式输出
     *
     * @return
     */
    public List<Activity> listOfActivity(User user) {
        String checkSql = "from Activity";
        List<Activity> list = this.getSession().createQuery(checkSql).list();
        if (list.size() == 0) {
            return null;
        } else {
            for (Activity list1 : list) {
                if (this.isAddActivity(user, list1)) {
                    list1.setIsAdded(1);
                }
            }
            return list;
        }
    }

    /**
     * 以list的方式将活动的参加人员输出
     *
     * @param act
     * @return
     */
    public List<String> listMembersOfAct(Activity act) {
        String checkSql = "select u.userName from User as u ,User_activity as act where act.act_id = ? and u.id = act.u_id";
        List<String> list = this.getSession().createQuery(checkSql).setParameter(0, act.getId()).list();
        if (list.size() == 0) {
            return null;
        } else {
            return list;
        }
    }

    /**
     * 添加成员到活动中
     *
     * @param user
     * @param acti_id
     * @return
     */
    public boolean addMemberInActivity(User user, int acti_id) {
        User_activity newOne = new User_activity(user.getId(), acti_id);
        this.getSession().save(newOne);
        return this.isAddActivity(user, (Activity) this.getSession().get(Activity.class, acti_id));
    }

    /**
     * 得到指定的活动对象
     *
     * @param id
     * @return
     */
    public Activity oneActivity(int id) {
        Activity result = (Activity) this.getSession().get(Activity.class, id);
        return result;
    }

    /**
     * 删除活动对象
     *
     * @param user
     * @param acti
     * @return
     */
    public boolean deleteMemberFromActivity(User user, Activity acti) {
        User_activity newOne = new User_activity(user.getId(), acti.getId());
        this.getSession().delete(newOne);
        return this.isAddActivity(user, acti);
    }

    /**
     * 将project的所有内容存到list中
     *
     * @return
     */
    public List<Project> listOfProject() {
        String checkSql = "from Project as pro order by pro.start_time desc";
        List<Project> list = this.getSession().createQuery(checkSql).list();
        if (list.isEmpty()) {
            return null;
        } else {
            return list;
        }
    }

    /**
     * 将pro_schedule的所有内容存入list中
     *
     * @return
     */
    public List<Pro_schedule> listOfProSchedule() {
        String checkSql = "from Pro_schedule as sche order by sche.time desc";
        List<Pro_schedule> list = this.getSession().createQuery(checkSql).list();
        if (list.isEmpty()) {
            return null;
        } else {
            return list;
        }
    }

    /**
     * 将user_project的所有内容存入list中
     *
     * @return
     */
    public List<User_project> listOfUserProject() {
        String checkSql = "from User_project";
        List<User_project> list = this.getSession().createQuery(checkSql).list();
        if (list.isEmpty()) {
            return null;
        } else {
            return list;
        }
    }

    /**
     * 将一个项目的负责人导入到list
     *
     * @param pro
     * @return
     */
    public List<String> listLeadersOfOneProject(Project pro) {
        String checkSql = "select u.userName from User as u,User_project as u_pro where u_pro.pro_id = ? and u_pro.isleader = 1 and u.id = u_pro.u_id";
        List<String> list = this.getSession().createQuery(checkSql).setParameter(0, pro.getId()).list();
        if (list.isEmpty()) {
            return null;
        } else {
            return list;
        }
    }

    /**
     * 将一个项目的负责人导入到list
     *
     * @param pro
     * @return
     */
    public List<String> listMembersOfOneProject(Project pro) {
        String checkSql = "select u.userName from User as u,User_project as u_pro where u_pro.pro_id = ? and u_pro.isleader = 0 and u.id = u_pro.u_id";
        List<String> list = this.getSession().createQuery(checkSql).setParameter(0, pro.getId()).list();
        if (list.isEmpty()) {
            return null;
        } else {
            return list;
        }
    }

    /**
     * 用户的个人项目
     *
     * @param user
     * @return
     */
    public List<Project> listProjectsOfUser(User user) {
        String checkSql = "select new Project(pro.id,pro.name, pro.isfinish, pro.description,pro.start_time) from Project as pro,User_project as u_pro where u_pro.u_id = ? and pro.id = u_pro.pro_id order by pro.id desc";
        List<Project> list = this.getSession().createQuery(checkSql).setParameter(0, user.getId()).list();
        return list;
    }

    /**
     * 添加进度描述
     *
     * @param newSche
     */
    public void addPro_schedule(Pro_schedule newSche) {
        this.getSession().saveOrUpdate(newSche);
    }

    /**
     * 添加项目
     *
     * @param newPro
     */
    public void addProject(Project newPro) {
        this.getSession().saveOrUpdate(newPro);
    }

    /**
     * 添加user_project
     *
     * @param newUserProject
     */
    public void addUser_project(User_project newUserProject) {
        this.getSession().saveOrUpdate(newUserProject);
    }

    /**
     * 得到全部成员
     *
     * @return
     */
    public List<User> listOfAllUsers() {
        String checkSql = "from User as u";
        return (this.getSession().createQuery(checkSql).list());
    }

    /**
     * 得到指定用户的Id
     *
     * @param name
     * @return
     */
    public int getIdOfOneUser(String name) {
        String checkSql = "from User as u where u.userName like ?";
        List<User> user = this.getSession().createQuery(checkSql).setParameter(0, name).list();
        return user.get(0).getId();
    }

    /**
     * 得到指定项目Id
     *
     * @param name
     * @return
     */
    public int getIdOfProjec(String name) {
        String checkSql = "from Project as pro where pro.name like ?";
        List<Project> pro = this.getSession().createQuery(checkSql).setParameter(0, name).list();
        return pro.get(0).getId();
    }

    public boolean registerValidate(User user) {
        String checkSql = "from Registration where u_id = ? ";
        List<Registration> rL = this.getSession().createQuery(checkSql)
                .setParameter(0, user.getId()).list();
        if (rL.size() == 0) {
            return false;
        } else {
            Registration rg = rL.get(rL.size() - 1);
            Date signdate = rg.getSignTime();
            Date nowDate = new Date();
            if ((nowDate.getTime() - signdate.getTime()) > 0
                    && (nowDate.getTime() - signdate.getTime()) <= 86400000) {//86400000为一天毫秒数
                return true;
            } else {
                return false;
            }
        }
    }

    public void addRegister(User user) {
        Session session = null;
        try {
            session = this.getSession();
            Registration registration = new Registration();
            registration.setSignTime(new Date());
            registration.setU_id(user.getId());
            session.save(registration);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Registration> showRegistrations(User user) {
        String checkSql = "from Registration where u_id = ? ";
        List<Registration> rL = this.getSession().createQuery(checkSql)
                .setParameter(0, user.getId()).list();
        return rL;
    }

    public List<Borrow> showBorrowInfo(User user) {
        String checkSql = "select b from Borrow b left join b.user u right join b.goods g where u.id = :userId";
        // + " and (b.lendTime,g.id) in (select max(b.lendTime),g.id from b group by b.goods)";
        List<Borrow> bl = this.getSession().createQuery(checkSql).setInteger("userId", user.getId())
                .list();

        return bl;
    }

    /**
     * 测试数据
     *
     * @param user
     */
    public void addTestDatas(User user) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Borrow borrow1 = new Borrow();
            borrow1.setLendTime(sdf.parse("2015-04-20"));
            borrow1.setReturnTime(sdf.parse("2015-04-23"));
            this.getSession().save(borrow1);
            Borrow borrow2 = new Borrow();
            borrow2.setLendTime(sdf.parse("2015-04-02"));
            this.getSession().save(borrow2);
        } catch (ParseException ex) {
            Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void updateInfo(User user) {
        Session session = this.getSession();
        User loginUser = (User) session.load(User.class, user.getId());
        loginUser.setAddress(user.getAddress());
        loginUser.setBlog(user.getBlog());
        loginUser.setEmail(user.getEmail());
        loginUser.setGender(user.getGender());
        loginUser.setGitAccount(user.getGitAccount());
        loginUser.setTel(user.getTel());
        loginUser.setUserGrade(user.getUserGrade());
        session.update(loginUser);
    }

    public boolean passwordValidate(String original, String originalInput) {
        if (!new MD5().getkeyBeanofStr(originalInput).equals(original)) {
            return false;
        }
        return true;
    }

    public void updatePassword(User user, String modify) {
        Session session = this.getSession();
        User loginUser = (User) session.load(User.class, user.getId());
        loginUser.setPassword(new MD5().getkeyBeanofStr(modify));
        session.update(loginUser);
    }


}
